package handlers

import (
	"commodity-master/cache"
	"commodity-master/models"
	"commodity-master/pkg"
	"github.com/gin-gonic/gin"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	var user models.User
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不为空",
		})
		return
	}
	redis_key := "user_id" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误三次禁止登录",
		})
		return
	}
	err := models.DB.Where("username=?", username).Find(user)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "无法查询用户",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户无法查询",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误三次封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return

}

func List(c *gin.Context) {
	var shop models.Shop
	models.DB.Find(shop)
	c.JSON(200, gin.H{
		"code": 400,
		"msg":  "查询成功",
		"data": shop,
	})
}
